# -*- encoding: utf-8 -*-
from django import forms
from django.contrib.auth.models import User
from idit.account.models import UserProfile
from idit.middleware import threadlocals

class SignupForm(forms.Form):
    email = forms.EmailField(label='邮箱')
    nickname = forms.CharField(max_length=10, label='昵称')
    password = forms.CharField(min_length=6, max_length=12, widget=forms.PasswordInput(), label='密码')
    passwordcopy = forms.CharField(min_length=6, max_length=12, widget=forms.PasswordInput(), label='请再输一次密码')
    
    def clean_email(self):
        email = self.cleaned_data['email']
        if User.objects.filter(username=email) :
            raise forms.ValidationError("该邮箱已经注册了!")
        return email
    
    def clean_nickname(self):
        nickname = self.cleaned_data['nickname']
        if UserProfile.objects.filter(nickname=nickname) :
            raise forms.ValidationError("该昵称已经被注册了!")
        return nickname
    
    def clean_passwordcopy(self):
        cd = self.cleaned_data
        password = cd['password']
        passwordcopy = cd['passwordcopy']
        if password != passwordcopy:
            raise forms.ValidationError("重复密码错误!")
        return passwordcopy


class EditPasswordForm(forms.Form):
    newpassword = forms.CharField(min_length=6, max_length=12, widget=forms.PasswordInput(), label='新密码(6-12个英文字母，符号或数字)')
    newpasswordcopy = forms.CharField(min_length=6, max_length=12, widget=forms.PasswordInput(), label='请再输入一次')
    
    def clean_newpasswordcopy(self):
        cd = self.cleaned_data
        newpassword = cd['newpassword']
        newpasswordcopy = cd['newpasswordcopy']
        if newpassword != newpasswordcopy:
            raise forms.ValidationError("重复密码错误!")
        return newpasswordcopy

class AccountForm(forms.Form):
    nickname = forms.CharField(max_length=10, label='昵称')
    def clean_nickname(self):
        nickname = self.cleaned_data['nickname']
        current_user = threadlocals.get_current_user()
        if current_user.userprofile.nickname != nickname and UserProfile.objects.filter(nickname=nickname) :
            raise forms.ValidationError("该昵称已经被注册了!")
        return nickname
    
